package qq.android.wan.qq.fragment;

import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TableRow;

import com.easemob.chat.EMChat;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMConversation;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;
import qq.android.wan.qq.adapter.ItemLvHistoryAdapter;
import qq.android.wan.qq.db.dao.SessionDao;
import qq.android.wan.qq.entity.FriendBean;
import qq.android.wan.qq.entity.SessionBean;
import qq.android.wan.qq.event.ChatEvent;
import qq.android.wan.qq.recever.NetChangeRecever;
import qq.android.wan.qq.R;
import qq.android.wan.qq.db.MyDateBaseHelper;
import qq.android.wan.qq.chat.activity.ChatActivity;
import qq.android.wan.qq.utils.IntentUtil;

/**
 * Created by Administrator on 2015/12/11.
 */
public class MessageFragment extends Fragment {
    private ListView lv_history;
    private ItemLvHistoryAdapter adapter;
    private LinearLayout layout_net;
    private NetChangeRecever netChangeRecever;
    private ArrayList<EMConversation> sessions;

    @Override
    public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_tab1_main, container);
        lv_history = (ListView) view.findViewById(R.id.lv_history);
        layout_net = (LinearLayout) view.findViewById(R.id.layout_net);
        if (!IntentUtil.isConnectionNet(getActivity())) {
            layout_net.setVisibility(View.VISIBLE);
        }
        layout_net.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Settings.ACTION_SETTINGS);
                startActivity(intent);
            }
        });
        lv_history.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent(getActivity(), ChatActivity.class);
                intent.putExtra("id",sessions.get(i).getUserName());
                intent.putExtra("nick",sessions.get(i).getUserName());
                getActivity().startActivity(intent);
                //设置未读数目为0
                EMConversation conversation = EMChatManager.getInstance().getConversationByType(1 + "", EMConversation.EMConversationType.Chat);
                int unread_num = conversation.getUnreadMsgCount();
                if (unread_num != 0) {
                    // sessions.get(i).setUnreadNum(0);
                    conversation.resetUnreadMsgCount();
                    adapter.notifyDataSetChanged();
                }

            }
        });
        sessions = new ArrayList<EMConversation>();
        mapToList(EMChatManager.getInstance().getAllConversations());
        adapter = new ItemLvHistoryAdapter(getActivity(), sessions);
        lv_history.setAdapter(adapter);
        netChangeRecever = new NetChangeRecever(layout_net);
        IntentFilter intentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        getActivity().registerReceiver(netChangeRecever, intentFilter);
        return view;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    public void onEventMainThread(ChatEvent event) {
        if (event == ChatEvent.UPDATE_SESSION_LASTMESSAGE) {
            mapToList(EMChatManager.getInstance().getAllConversations());
            adapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        getActivity().unregisterReceiver(netChangeRecever);
        EventBus.getDefault().unregister(this);
    }

    public void mapToList(Hashtable<String, EMConversation> maps) {
        sessions.removeAll(sessions);
        Iterator it = maps.keySet().iterator();
        while (it.hasNext()) {
            String key = it.next().toString();
            sessions.add(maps.get(key));
        }

        Collections.sort(sessions, new Comparator<EMConversation>() {
            @Override
            public int compare(EMConversation e1, EMConversation e2) {
                if (e1.getLastMessage().getMsgTime() > e2.getLastMessage().getMsgTime()) {
                    return -1;
                } else if (e1.getLastMessage().getMsgTime() < e2.getLastMessage().getMsgTime()) {
                    return 1;
                } else {
                    return 0;
                }
            }
        });
    }
}
